package com.example.heipictureserver.api.imagesearch.sub;

import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSONUtil;
import com.example.heipictureserver.exception.BusinessException;
import com.example.heipictureserver.exception.ErrorCode;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * 获取以图搜图页面地址（step 1）
 *
 * <p>调用百度图搜接口，将图片 URL 作为参数提交，返回百度搜索结果页面的地址</p>
 *
 * @Author bwg
 * @Date 2025/2/1 15:06
 */
@Slf4j
public class GetImagePageUrlApi {

 /**
  * 获取以图搜图页面地址
  *
  * @param imageUrl 待搜索图片的地址（需要经过 URL 编码）
  * @return 百度图搜返回的搜索结果页面 URL
  */
 public static String getImagePageUrl(String imageUrl) {
  // 构造请求参数
  Map<String, Object> formData = new HashMap<>();
  formData.put("image", imageUrl);
  formData.put("tn", "pc");
  formData.put("from", "pc");
  formData.put("image_source", "PC_UPLOAD_URL");

  // 获取当前时间戳作为 uptime 参数（防止缓存）
  long uptime = System.currentTimeMillis();
  // 请求地址
  String url = "https://graph.baidu.com/upload?uptime=" + uptime;
  try {
   // 发送 POST 请求，同时添加多个请求头以模拟浏览器请求
   HttpResponse httpResponse = HttpRequest.post(url)
           .header("accept", "*/*")
           .header("accept-language", "zh-CN,zh;q=0.9")
           .header("acs-token", "1738989030331_1739000508347_SXucBYIRBt33sePm1IE4tcrVQhCWR6NTm79IYpZg+KvIxHpkB68uuEgw7k2iVyR6wiTVGOiQeRZrl0rebrucReO0ISiHTeyDA7bGODul7Xs0vnCxZfp5/cOGYtb6CaHGizYE4CEmEU3FdCcCNvWXNGdH2Bn1WonvA4P951HdSeGO1G2IMqvTOyZjzxwTxApk83YyWseXTIDam+wp/80yCAZOWjYkgqDDTFi13dwZ+S7ETpT9OfFbBMoBSNqwiONwwh577AVn45QnsNIC1q+GHGfXf6T6zR16/+6Zv9Byqz6lsUb946D6OjzgmZnUG7IvdtYUlndfaYJtxVvAR0dstL1YcOC0bxiRI7H+0Qi3DkGwdygvWoSa4+RCZ/tuLGwm8ItdNLpsLaPPNyx+dbRptfA8VdhYDua9Bf8kDNaa2PwzTrPDA1+Xb6yhKB7paPbfv1hKRTl+SW7Fr8BTWVQE0xeCnzWibdle8I2JjnDvXvT/48FL4Qo8jfBjoI1Z52PZ")
           .header("cache-control", "no-cache")
           .header("cookie", "BIDUPSID=12A5DCB5A1ACE4BDD0939B08FAC1B5DC; PSTM=1726727746; BAIDUID=12A5DCB5A1ACE4BD72B2219461F23B4A:FG=1; ...")
           .header("dnt", "1")
           .header("origin", "https://graph.baidu.com")
           .header("pragma", "no-cache")
           .header("priority", "u=1, i")
           .header("referer", "https://graph.baidu.com/pcpage/index?tpl_from=pc")
           .header("sec-ch-ua", "\"Not A(Brand\";v=\"8\", \"Chromium\";v=\"132\"")
           .header("sec-ch-ua-mobile", "?1")
           .header("sec-ch-ua-platform", "\"Android\"")
           .header("sec-fetch-dest", "empty")
           .header("sec-fetch-mode", "cors")
           .header("sec-fetch-site", "same-origin")
           .header("user-agent", "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/132.0.0.0 Mobile Safari/537.36")
           .header("x-requested-with", "XMLHttpRequest")
           .form(formData)
           .timeout(5000)
           .execute();

   System.out.println("返回结果：" + httpResponse.body());

   // 检查响应状态码是否为 200 OK
   if (httpResponse.getStatus() != HttpStatus.HTTP_OK) {
    throw new BusinessException(ErrorCode.OPERATION_ERROR, "接口调用失败");
   }
   // 解析响应内容
   String body = httpResponse.body();
   Map<String, Object> result = JSONUtil.toBean(body, Map.class);
   if (result == null || !Integer.valueOf(0).equals(result.get("status"))) {
    throw new BusinessException(ErrorCode.OPERATION_ERROR, "接口调用失败");
   }
   // 获取 data 中的 url 字段
   Map<String, Object> data = (Map<String, Object>) result.get("data");
   String rawUrl = (String) data.get("url");
   // 对 URL 进行解码处理
   String searchResultUrl = URLUtil.decode(rawUrl, StandardCharsets.UTF_8);
   if (StrUtil.isBlank(searchResultUrl)) {
    throw new BusinessException(ErrorCode.OPERATION_ERROR, "未返回有效的结果地址");
   }
   return searchResultUrl;
  } catch (Exception e) {
   log.error("调用百度以图搜图接口失败", e);
   throw new BusinessException(ErrorCode.OPERATION_ERROR, "搜索失败");
  }
 }

 public static void main(String[] args) {
  // 测试以图搜图功能，待搜索图片地址（注意：若地址中包含特殊字符，需先进行 URL 编码）
  String imageUrl = "https://www.codefather.cn/logo.png";
  String searchResultUrl = getImagePageUrl(imageUrl);
  System.out.println("搜索成功，结果 URL：" + searchResultUrl);
 }
}
